import { useState } from 'react';
import apiClient from '../api/axios'; // 引入apiClient
import { useNavigate, Link } from 'react-router-dom'; // 引入useNavigate用于跳转
import { useAuth } from '../context/AuthContext'; // 引入useAuth

function LoginPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const { login } = useAuth(); // 从Context中获取login函数
  const navigate = useNavigate(); // 获取navigate函数

  const handleSubmit = async (e) => { // 将函数改为async
    e.preventDefault();
    setError(''); // 清空之前的错误信息
    try {
      // 使用apiClient发送POST请求
      const response = await apiClient.post('/users/login', { email, password });
      // 检查响应数据是否存在
      if (response && response.data) {
        login(response.data.token); // 调用Context的login函数来更新全局token
        navigate('/'); // 登录成功后跳转到主页
      } else {
        setError('登录响应数据格式错误');
      }
    } catch (err) {
      console.error('登录失败:', err.response?.data || err.message);
      // 更安全的错误处理
      const errorMsg = err.response?.data?.msg || err.message || '登录失败，请稍后再试';
      setError(errorMsg); // 显示错误信息
    }
  };

  return (
    <div style={{ 
      maxWidth: '400px', 
      margin: '50px auto', 
      padding: '30px',
      backgroundColor: '#fff',
      borderRadius: '8px',
      boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
    }}>
      <h1 style={{ 
        textAlign: 'center', 
        marginBottom: '30px',
        color: '#333'
      }}>
        🔐 用户登录
      </h1>
      
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '20px' }}>
          <label style={{ 
            display: 'block', 
            marginBottom: '8px',
            fontWeight: 'bold'
          }}>
            📧 邮箱:
          </label>
          <input 
            type='email' 
            value={email} 
            onChange={(e) => setEmail(e.target.value)}
            style={{ 
              width: '100%', 
              padding: '12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              fontSize: '16px',
              boxSizing: 'border-box'
            }}
            placeholder="请输入邮箱"
            required
          />
        </div>
        
        <div style={{ marginBottom: '20px' }}>
          <label style={{ 
            display: 'block', 
            marginBottom: '8px',
            fontWeight: 'bold'
          }}>
            🔑 密码:
          </label>
          <input 
            type='password' 
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            style={{ 
              width: '100%', 
              padding: '12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              fontSize: '16px',
              boxSizing: 'border-box'
            }}
            placeholder="请输入密码"
            required
          />
        </div>
        
        <button 
          type='submit' 
          style={{ 
            width: '100%', 
            padding: '12px', 
            backgroundColor: '#007bff', 
            color: 'white', 
            border: 'none', 
            borderRadius: '4px', 
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: 'bold'
          }}
        >
          🚀 登录
        </button>
      </form>
      
      <div style={{ 
        textAlign: 'center', 
        marginTop: '20px'
      }}>
        <p>
          还没有账户？ 
          <Link to="/register" style={{ 
            color: '#007bff', 
            textDecoration: 'none',
            fontWeight: 'bold'
          }}>
            立即注册
          </Link>
        </p>
      </div>
      
      {error && <div style={{ 
        marginTop: '20px',
        padding: '12px',
        backgroundColor: '#f8d7da',
        color: '#721c24',
        border: '1px solid #f5c6cb',
        borderRadius: '4px',
        textAlign: 'center'
      }}>
        ❌ {error}
      </div>}
    </div>
  );
}
export default LoginPage;